<template>
  <div class="login-container">
    <div class="left">
      <div class="title-box">
        <img src="@/assets/img/login_icon.png" alt="" />
        <div class="title">黑马面面</div>
        <div class="line"></div>
        <div class="sub-title">用户登录</div>
      </div>
      <div class="form">
        <!-- 
          model 绑定的数据，里面属性要根据后台接口来
          rules 校验规则
          inline 是否是横向展示
          status-icon 是否展示提示图标
        -->
        <el-form
          :model="form"
          ref="form"
          :rules="rules"
          :inline="false"
          size="normal"
          class="login-form"
        >
          <!-- 这个el-form-item 上面的prop 很重要，起到两个作用，一个是校验，一个是清除 -->
          <el-form-item prop="phone">
            <el-input
              prefix-icon="el-icon-user"
              v-model="form.phone"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <!-- 密码部分 -->
          <el-form-item prop="password">
            <el-input
              prefix-icon="el-icon-lock"
              v-model="form.password"
              placeholder="请输入密码"
              show-password
            ></el-input>
          </el-form-item>
          <!-- 验证码部分 -->
          <el-row>
            <el-col :span="16">
              <el-form-item prop="code">
                <el-input
                  prefix-icon="el-icon-key"
                  v-model="form.code"
                  placeholder="请输入验证码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <!-- 验证码图片 -->
              <img
                class="captcha"
                :src="loginCaptchaUrl"
                @click="changeLoginCaptchaUrl"
                alt=""
              />
            </el-col>
          </el-row>
          <el-form-item prop="checked">
            <el-checkbox
              v-model="form.checked"
              style="margin-right:5px"
            ></el-checkbox
            >我已阅读并同意<el-link
              href="https://element.eleme.io"
              target="_blank"
              type="primary"
              >用户协议</el-link
            >和<el-link
              href="https://element.eleme.io"
              target="_blank"
              type="primary"
              >隐私条款</el-link
            >
          </el-form-item>
          <el-form-item>
            <el-button style="width:100%" @click="login" type="primary"
              >登录</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              style="width:100%"
              type="primary"
              @click="$refs.registerRef.dialogVisible = true"
              >注册</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="right">
      <img src="@/assets/img/login_bg.png" alt="" />
    </div>
    <register ref="registerRef"></register>
  </div>
</template>

<script>
import register from './Register'
export default {
  components: {
    register
  },
  name: 'Login',
  data () {
    return {
      loginCaptchaUrl: process.env.VUE_APP_BASEURL + '/captcha?type=login', // 登录验证码地址
      form: {
        phone: '18511111111', // 手机号
        password: '12345678', // 密码
        code: '', // 验证码
        checked: true
      },
      rules: {
        phone: [
          {
            validator: (rule, value, callback) => {
              //rule 规则 基本用不到, value 输入的值, callback 回调函数 失败 callback(new Error('错误信息')),成功 callback()
              if (!value) {
                callback(new Error('手机号不能为空')) //失败
                return
              }
              const reg = /^1[3-9][0-9]{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号不合法')) //失败
                return
              }
              callback() //成功
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '密码长度必须在6-16位之间',
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          {
            min: 4,
            max: 4,
            message: '验证码的长度必须是4位',
            trigger: 'blur'
          }
        ],
        checked: [
          {
            validator: (rule, value, callback) => {
              value ? callback() : callback(new Error('必须勾选用户协议'))
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    changeLoginCaptchaUrl () {
      // 缓存出现的两个条件： GET + 地址没变
      this.loginCaptchaUrl =
        process.env.VUE_APP_BASEURL + '/captcha?type=login&t=' + Date.now()
    },
    login () {
      // async 要加在写了await的函数上
      this.$refs.form.validate(async valid => {
        //valid 值为true/false
        if (!valid) return

        // 使用async & await 配合去完成发送请求的任务
        // await 后面接的是promise对象
        const res = await this.$axios.post('/login', this.form)
        if (res.code == 200) {
          //成功
          this.$message.success('登录成功!')
          //保存token
          // localStorage.setItem('heimapc-token', res.data.token)
          saveToken(res.data.token)
          //跳转到layout
          this.$router.push('/layout')
        } else {
          //提示错误信息
          this.$message({
            message: res.message,
            type: 'error',
            duration: 1000
          })
          //刷新验证码
          this.changeLoginCaptchaUrl()
        }

        //发请求
        // this.$axios.post('/login', this.form).then(res => {
        // if (res.code == 200) {
        //   //成功
        //   this.$message.success('登录成功!')
        //   //保存token
        //   localStorage.setItem('heimapc-token', res.data.token)
        //   //跳转到layout
        //   this.$router.push('/layout')
        // } else {
        //   //提示错误信息
        //   this.$message({
        //     message: res.message,
        //     type: 'error',
        //     duration: 1000
        //   })
        //   //刷新验证码
        //   this.changeLoginCaptchaUrl()
        // }
        // })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background: linear-gradient(225deg, #1493fa, #01c6fa);
  .left {
    width: 478px;
    height: 550px;
    background: #f5f5f5;
    padding: 48px;
    .title-box {
      display: flex;
      align-items: center;
      img {
        width: 22px;
        height: 17px;
        margin-right: 16px;
      }
      .title {
        font-size: 24px;
        margin-right: 14px;
      }
      .line {
        width: 1px;
        background-color: #c7c7c7;
        height: 27px;
        margin-right: 12px;
      }
      .sub-title {
        font-size: 22px;
      }
    }
    .login-form {
      margin-top: 29px;
      .captcha {
        width: 100%;
        height: 40px;
        margin-left: 10px;
      }
    }
  }
}
</style>
